package com.power.authservice.config;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.power.authservice.impl.UserDetailsServiceImpl;
import com.power.authservice.model.LoginResult;
import com.power.constant.AuthConstants;
import com.power.constant.BusinessEnum;
import com.power.constant.HttpConstans;
import com.power.model.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.AccountStatusException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import java.io.PrintWriter;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Configuration
public class AuthSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsServiceImpl userDetailsService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 重写方法使用自己的认证流程
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //（com/power/gatewayservice/filter/AuthFilter.java）登录拦截器里面路由到这里，会发现这边自定义的实现类
         auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //关闭跨域请求伪造
            http.cors().disable();
        //关闭跨域请求
            http.csrf().disable();
        //关闭session使用策略
        http.sessionManagement().sessionCreationPolicy(org.springframework.security.config.http.SessionCreationPolicy.STATELESS);
        //配置登录信息
        http.formLogin().loginProcessingUrl(AuthConstants.LOGIN_URL)//登录的url
                .successHandler(authenticationSuccessHandler())//登录成功的处理器
                .failureHandler(authenticationFailureHandler());//登录失败的处理器
        //配置登出信息
        http.logout().logoutUrl(AuthConstants.LOGOUT_RUL)//登出url
                .logoutSuccessHandler(logoutSuccessHandler());//登出失败处理器

        //要求所有请求都需要进行身份认证
        http.authorizeRequests().anyRequest().authenticated();

    }

    /**
     * 登录成功处理器
     * @return
     */
    @Bean
    public AuthenticationSuccessHandler authenticationSuccessHandler(){
        return (request, response, authentication) -> {
            response.setContentType(HttpConstans.APPLICATION_JSON);
            response.setCharacterEncoding(HttpConstans.UTF_8);
            //token的key
            String token = UUID.randomUUID().toString();
            //token的值（用户的信息）
            String user = JSONObject.toJSONString(authentication.getPrincipal());
            redisTemplate.opsForValue().set(AuthConstants.Login_Token_prefix+token,user,AuthConstants.TOKEN_TIME, TimeUnit.SECONDS);
            LoginResult loginResult = new LoginResult(token,AuthConstants.TOKEN_TIME);
            Result<Object> result = Result.success(loginResult);
            ObjectMapper mapper = new ObjectMapper();
            String s = mapper.writeValueAsString(result);
            PrintWriter writer = response.getWriter();
            writer.write(s);
            writer.flush();
            writer.close();

        };
    }
    /**
     * 登录失败处理器
     * @return
     */
    @Bean
    public AuthenticationFailureHandler authenticationFailureHandler()
    {
//        return new AuthenticationFailureHandler() {
//            @Override
//            public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
//
//            }
//        };
        return (request,response,exception)->{
            response.setContentType(HttpConstans.APPLICATION_JSON);
            response.setCharacterEncoding(HttpConstans.UTF_8);
            Result<Object> result = new Result<>();
            result.setCode(BusinessEnum.OPERATION_FAIL.getCode());
            if (exception instanceof BadCredentialsException)
            {
                result.setMsg("用户名或密码错误");
            } else if (exception instanceof UsernameNotFoundException) {
                result.setMsg("用户不存在");
            } else if (exception instanceof AccountExpiredException) {
                result.setMsg("账号异常请联系管理员");
            } else if (exception instanceof AccountStatusException) {
                result.setMsg("账号异常请联系管理员");
            } else if (exception instanceof InternalAuthenticationServiceException) {
                result.setMsg(exception.getMessage());
            }
            else {
                result.setMsg(BusinessEnum.OPERATION_FAIL.getDesc());
            }
            ObjectMapper mapper = new ObjectMapper();
            //使用ObjectMapper 类型转换类将Result类转换成字符串
            String resultString = mapper.writeValueAsString(result);
            PrintWriter writer = response.getWriter();
            writer.write(resultString);
            writer.flush();
            writer.close();

        };
    }
    /**
     * 登出成功处理器
     * @return
     */
    @Bean
    public LogoutSuccessHandler logoutSuccessHandler()
    {
        return (request,response,authentication)->{
            response.setContentType(HttpConstans.APPLICATION_JSON);
            response.setCharacterEncoding(HttpConstans.UTF_8);
            String token = request.getHeader(AuthConstants.AUTHORIZATION);
            if (StringUtils.isNotBlank(token))
            {
                token = token.replace(AuthConstants.BEARER,"");
                redisTemplate.delete(AuthConstants.Login_Token_prefix+token);
            }
            Result<Object> result = Result.success(null);
            ObjectMapper mapper = new ObjectMapper();
            String resultString = mapper.writeValueAsString(result);
            PrintWriter writer = response.getWriter();
            writer.write(resultString);
            writer.flush();
            writer.close();
        };
    }
    @Bean
    public BCryptPasswordEncoder passwordEncoder()
    {
        return new BCryptPasswordEncoder() ;
    }
}
